//
//  WBStatusPictureView.swift
//  Weibo
//
//  Created by Albert Zhu on 16/10/20.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import UIKit

class WBStatusPictureView: UIView {
    @IBOutlet weak var heightConstr: NSLayoutConstraint!
    
    var viewModel: WBStatusViewModel? {
        didSet {
            calcViewSize()
        }
    }
    
    /// 配图的URL数组
    var urls: [WBStatusPicture]? {
        didSet {
            for v in subviews {
                v.isHidden = true
            }
            
            var index = 0
            for url in urls ?? [] {
                let iv = subviews[index] as! UIImageView
                
                if index == 1 && urls?.count == 4 {
                    index += 1
                }
                
                iv.az_setImage(urlString: url.thumbnail_pic, placeholderImage: nil)
                
                iv.isHidden = false
                iv.contentMode = .scaleAspectFill
                iv.clipsToBounds = true
                
                index += 1
            }
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
    
        setupUI()
    }
    
    /// 根据配图大小调整显示内容
    private func calcViewSize() {
        
        if viewModel?.picURLs?.count == 1 {
            
            let viewSize = viewModel?.pictureSize ?? CGSize()
            
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: WBStatusPictureViewOutterMargin, width: viewSize.width, height: viewSize.height)
        }else{
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: WBStatusPictureViewOutterMargin, width: WBStatusPictureItemWidth, height: WBStatusPictureItemWidth)
        }
        
        heightConstr.constant = viewModel?.pictureSize.height ?? 0
    }
    
    /// Cell中所有的控件都是提前准备好，根据数据决定是否展示，动态创建的话会影响性能
    private func setupUI() {
        
        backgroundColor = superview?.backgroundColor
        
        clipsToBounds = true
        
        let rect = CGRect(x: 0, y: WBStatusPictureViewOutterMargin, width: WBStatusPictureItemWidth, height: WBStatusPictureItemWidth)
        let jianju = WBStatusPictureItemWidth + WBStatusPictureViewInnerMargin
        
        for i in 0..<9 {
            let iv = UIImageView()
            iv.frame = rect.offsetBy(dx: CGFloat(i % 3) * jianju, dy: CGFloat(i / 3) * jianju)
            
            addSubview(iv)
        }
    }
}
